import { DataService } from '@services/data.service';
import { Component, OnInit, ElementRef, Renderer2, AfterViewChecked } from '@angular/core';
import { ModalController, NavController, PopoverController } from '@ionic/angular';

import { QRScannerModal } from '@modals/qr-scanner/qr-scanner';
import { CacheService } from '@services/cache.service';
import { MyNoteService } from '@services/myNote.service';
import { PicUploadService } from '@services/picUpload.service';
import { Router } from '@angular/router';
import { PopoverPage } from '@pages/home/popover/popover';

@Component({
    selector: 'index-operation',
    templateUrl: 'page.html',
    styleUrls: ['style.scss']
})
export class IndexOperationPage implements OnInit, AfterViewChecked {
    person = {
        headStyle: {
            // 'background-image': 'url('assets/imgs/default.png')'
        },
        headStylebg: {
            // 'background': '#1fb5ff'
        }
    };
    TargetList;
    canGoBack = false;
    PList = [];
    groupList = [];
    // 设置平台界面指标
    indexDataList = [
        { 'IndexCode': '103293', 'IndexName': '项目移交', 'Data1': 0, 'Data2': 0, 'isShow': false },
        { 'IndexCode': '103016', 'IndexName': '数据栈', 'Data1': 0, 'Data2': 0, 'isShow': false },
        { 'IndexCode': '103115', 'IndexName': '传感器', 'Data1': 0, 'Data2': 0, 'isShow': false },
        { 'IndexCode': '105137', 'IndexName': '物联工单完成', 'Data1': 0, 'Data2': 0, Unit1: '%', 'isShow': false },
        { 'IndexCode': '105004', 'IndexName': '在线用户', 'Data1': 0, 'Data2': 0, 'isShow': false },
    ];
    TargetInterval;
    informOption = {
        step: 1,
        timer: 50,
        left: 25,
        right: 10
    };

    blocInfo = {
        BlocName: '',
        Comprehensive: { Title: '', Evaluation: '', Percent: null },
        BlocBGP: '',
        BlocUrl: '',
        Announcement: '关于开展预交物业费送礼品活动通知',
    };

    constructor(
        private modalCtrl: ModalController,
        private navCtrl: NavController,
        private el: ElementRef,
        private renderer: Renderer2,
        private cache: CacheService,
        private myNote: MyNoteService,
        private picUploadService: PicUploadService,
        private router: Router,
        private dataService: DataService,
        private popoverCtrl: PopoverController,
    ) {
        if (this.cache.functionPoint) {
            this.PList = this.cache.functionPoint[this.cache.functionPoint.length - 3].children;
            const Plist = [];
            const Tlist = [];
            for (let i = 0; i < this.PList.length; i++) {
                if (this.PList[i].menuType === 8) {
                    // 平台层指标
                    Tlist.push(this.PList[i]);
                } else {
                    Plist.push(this.PList[i]);
                }
            }
            this.PList = Plist;
            this.TargetList = Tlist;
            for (let i = 0; i < this.indexDataList.length; i++) {
                for (let j = 0; j < this.TargetList.length; j++) {
                    if (this.TargetList[j].menuName === this.indexDataList[i].IndexName) {
                        this.indexDataList[i].isShow = true;
                    }
                }
            }
        }

        this.cache.companys.subscribe(val => {
            this.groupList = val;
        });
    }

    ngOnInit() {
        // this.canGoBack = this.navCtrl.canGoBack();
    }

    ngAfterViewChecked() {
        this.WordResult();
    }

    ionViewWillEnter() {
        const elements = document.querySelectorAll('ion-tab-bar');
        if (elements != null) {
            Object.keys(elements).map((key) => {
                elements[key].style.display = 'flex';
            });
        }
        this.setHeadAndBack();
        this.getTarget();
    }

    ionViewWillLeave() {
        const elements = document.querySelectorAll('ion-tab-bar');
        if (elements != null) {
            Object.keys(elements).map((key) => {
                elements[key].style.display = 'none';
            });
        }
        if (this.TargetInterval) {
            clearInterval(this.TargetInterval);
        }
    }

    setHeadAndBack() {
        this.person.headStylebg = { 'background': 'linear-gradient(#54BFF4, #1FB5FF)' };
        this.person.headStyle = { 'background-image': 'url(assets/imgs/default.png)' };
        this.picUploadService.getAvatar().subscribe(imgdata => {
            if (imgdata.isDefault) {
                this.person.headStylebg = { 'background-image': 'linear-gradient(#54BFF4, #1FB5FF)' };
            } else {
                this.person.headStylebg = { 'background-image': 'url(' + imgdata.url + ')' };
            }
            this.person.headStyle = { 'background-image': 'url(' + imgdata.url + ')' };
        });
    }

    // 获取平台界面指标
    getTarget() {
        this.dataService.getTarget(103293, 1).subscribe(res => {
            // console.log('获取项目移交指标');
            if (res.data) {
                this.indexDataList[0].Data1 = res.data.onlineNum;
                this.indexDataList[0].Data2 = res.data.totalNum;
            }
        });
        this.dataService.getTarget(103016, 1).subscribe(res => {
            // console.log('获取数据栈指标');
            if (res.data) {
                this.indexDataList[1].Data1 = res.data.totalNum - res.data.onlineNum;
                this.indexDataList[1].Data2 = res.data.totalNum;
            }
        });
        this.dataService.getTarget(103115, 1).subscribe(res => {
            // console.log('获取传感器指标');
            if (res.data) {
                this.indexDataList[2].Data1 = res.data.totalNum - res.data.onlineNum;
                this.indexDataList[2].Data2 = res.data.totalNum;
            }
        });
        this.dataService.getTarget(105137, 1).subscribe(res => {
            // console.log('获取物联工单完成指标');
            if (res.data && res.data.totalNum) {
                this.indexDataList[3].Data1 = Math.round(res.data.recoveryNum / res.data.totalNum * 100);
            } else {
                this.indexDataList[3].Data1 = 0;
            }
        });
        this.dataService.getTarget(105004, 1).subscribe(res => {
            // console.log('获取在线用户指标');
            if (res.data) {
                this.indexDataList[4].Data1 = res.data.onlineNum;
                this.indexDataList[4].Data2 = res.data.totalNum;
            }
        });
    }

    scrollHandler(event) {
        const columnTop = event.scrollTop;
        const opacity = columnTop / 186 >= 1 ? 1 : columnTop / 186;
        const topEle = this.el.nativeElement.querySelector('.project-title');
        this.renderer.setStyle(topEle, 'background', 'rgba(31,181,255,' + opacity + ')');
    }

    async scan() {
        const QRmodal = await this.modalCtrl.create({
            component: QRScannerModal
        });
        QRmodal.present();
        const res = await QRmodal.onDidDismiss();
        if (res.data) {
        }
    }

    goPage(data) {
        if (data.url.length > 1) {
            // this.navCtrl.push(data.url);
            this.navCtrl.navigateForward([data.url]);
        } else {
            console.log(data.menuName + ',该功能点url不正确或未配置');
        }
    }

    goGroupPage(data): void {
        this.cache.currentCompany = data;
        // this.navCtrl.push('indexGroup', {
        //     companyId: data.companyId,
        //     companyName: data.companyName
        // });
        const params = {
            companyId: data.companyId,
            companyName: data.companyName
        };
        this.navCtrl.navigateForward(['tabs/home/indexGroup'], {
            queryParams: params
        });
    }

    logScrolling(e) {
        const el = this.el.nativeElement.querySelector('ion-toolbar');
        const elH = this.el.nativeElement.querySelector('ion-header');
        if (e.detail.scrollTop >= 270) {
            this.renderer.addClass(el, 'active');
            this.renderer.addClass(elH, 'active');
        } else {
            this.renderer.removeClass(el, 'active');
            this.renderer.removeClass(elH, 'active');
        }
    }

    async Search(i) {
        const popover = await this.popoverCtrl.create({
            component: PopoverPage,
            componentProps: {
                type: i,
                Page: 0
            },
            backdropDismiss: false,
            cssClass: 'home-popover'
        });
        popover.present();
        const res = await popover.onDidDismiss();
        if (res.data) {
            const data = res.data;
            if (data) {
                switch (data.type) {
                    case '1':
                        this.cache.currentCompany = data.item;
                        this.navCtrl.navigateForward(['tabs/home/indexGroup'],
                            {
                                queryParams: {
                                    type: data.type,
                                    companyId: data.item.companyId,
                                    companyName: data.item.companyName
                                }
                            });
                        break;
                    case '2':
                        this.cache.currentProject = data.item;
                        this.navCtrl.navigateForward(['tabs/home/indexProject'],
                            {
                                queryParams: {
                                    type: data.type,
                                    projectId: data.item.projectId,
                                    projectName: data.item.projectName,
                                }
                            });
                        break;
                    case '3':
                        this.goPage(data.item);
                        break;
                }
            }
        }

    }

    // 文字处理
    WordResult() {
        // 计算内容的高度 来判断是多少行
        const wareNameText = [];
        const heightSome = [];
        const wareName = this.el.nativeElement.querySelectorAll('.each-name');
        for (let i = 0; i < wareName.length; i++) {
            wareNameText[i] = wareName[i].innerHTML;
            heightSome[i] = wareName[i].clientHeight;
            if (heightSome[i] > 40) {
                // 这个42数字是两行的时候的高度，根据你设定的字体大小有关
                for (let k = 0; heightSome[i] > 40; k++) {
                    // 每次删掉最后一个然后返回
                    wareNameText[i] = wareNameText[i].substring(0, wareNameText[i].length - 1);
                    // 重新返回的字符在写在span里面 ，计算新的高度
                    wareName[i].innerHTML = wareNameText[i];
                    heightSome[i] = wareName[i].clientHeight;
                }
                // 得到正好符合高度的字符，删除最后一个变为省略号 填充在页面里
                const newText = [];
                newText[i] = wareNameText[i].substring(0, wareNameText[i].length - 1) + '...';
                wareName[i].innerHTML = newText[i];
            }
        }
    }


    goBack() {
        this.navCtrl.pop();
    }
}
